/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-10 16:26:02
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-05-10 16:26:06
 * @FilePath: /data-center-web/src/utils/resize.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ref } from 'vue';
export default function () {
    const chart = ref<any>();
    const sidebarElm = ref<Element>();

    const chartResizeHandler = () => {
        if (chart.value) {
            chart.value.resize();
        }
    };

    const sidebarResizeHandler = (e: TransitionEvent) => {
        if (e.propertyName === 'width') {
            chartResizeHandler();
        }
    };

    const initResizeEvent = () => {
        window.addEventListener('resize', chartResizeHandler, {
            passive: true
        });
    };

    const destroyResizeEvent = () => {
        window.removeEventListener('resize', chartResizeHandler);
    };

    const initSidebarResizeEvent = () => {
        sidebarElm.value =
            document.getElementsByClassName('sidebar-container')[0];
        if (sidebarElm.value) {
            sidebarElm.value.addEventListener(
                'transitionend',
                sidebarResizeHandler as EventListener,
                { passive: true }
            );
        }
    };

    const destroySidebarResizeEvent = () => {
        if (sidebarElm.value) {
            sidebarElm.value.removeEventListener(
                'transitionend',
                sidebarResizeHandler as EventListener
            );
        }
    };

    const mounted = () => {
        initResizeEvent();
        initSidebarResizeEvent();
    };

    const beforeDestroy = () => {
        destroyResizeEvent();
        destroySidebarResizeEvent();
    };

    const activated = () => {
        initResizeEvent();
        initSidebarResizeEvent();
    };

    const deactivated = () => {
        destroyResizeEvent();
        destroySidebarResizeEvent();
    };

    return {
        chart,
        mounted,
        beforeDestroy,
        activated,
        deactivated
    };
}
